//
//  NSObject+Common.m
//  Coding
//
//  Created by Zhan Yu on 15/12/25.
//  Copyright © 2015年 Coding. All rights reserved.
//
#define kPath_ImageCache @"ImageCache"
#define kPath_ResponseCache @"ResponseCache"

#import "NSObject+Common.h"

#import "MBProgressHUD+MJ.h"
#import "JDStatusBarNotification.h"
#import "CDAFNClient.h"

@implementation NSObject (Common)

#pragma mark 提示 M
+ (NSString *)promptWithError:(NSError *)error
{
    if (error && error.userInfo)
    {
        NSMutableString *tipStr = [[NSMutableString alloc] init];
        if ([error.userInfo objectForKey:@"msg"])
        {
            NSArray *msgArray = [[error.userInfo objectForKey:@"msg"] allValues];
            NSUInteger num = [msgArray count];
            for (int i = 0; i < num; i++)
            {
                NSString *msgStr = [msgArray objectAtIndex:i];
                if (i+1 < num)
                {
                    [tipStr appendString:[NSString stringWithFormat:@"%@\n", msgStr]];
                }
                else
                {
                    [tipStr appendString:msgStr];
                }
            }
        }
        else
        {
            if ([error.userInfo objectForKey:@"NSLocalizedDescription"])
            {
                tipStr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            }
            else
            {
                [tipStr appendFormat:@"ErrorCode%ld", (long)error.code];
            }
        }
        return tipStr;
    }
    return nil;
}

#pragma mark - 是否显示错误信息
+ (BOOL)showError:(NSError *)error
{
    if ([JDStatusBarNotification isVisible])
    {   //如果statusBar上面正在显示信息，则不再用hud显示error
        CDLog(@"如果statusBar上面正在显示信息，则不再用hud显示error");
        return NO;
    }
    NSString * promptStr = [NSObject promptWithError:error];
    [NSObject showHudPromptStr:promptStr];
    return YES;
}

#pragma mark - 显示错误信息
+ (void)showHudPromptStr:(NSString *)promptStr
{
    if (promptStr && promptStr.length > 0)
    {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:CDKeyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.detailsLabelFont = [UIFont boldSystemFontOfSize:15.0];
        hud.detailsLabelText = promptStr;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1.0];
    }
}

+ (void)showStatusBarQueryStr:(NSString *)tipStr
{
    [JDStatusBarNotification showWithStatus:tipStr styleName:JDStatusBarStyleSuccess];
    [JDStatusBarNotification showActivityIndicator:YES indicatorStyle:UIActivityIndicatorViewStyleWhite];
}

+ (void)showStatusBarSuccessStr:(NSString *)tipStr
{
    if ([JDStatusBarNotification isVisible])
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
        {
            [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
            [JDStatusBarNotification showWithStatus:tipStr dismissAfter:1.5 styleName:JDStatusBarStyleSuccess];
        });
    }
    else
    {
        [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
        [JDStatusBarNotification showWithStatus:tipStr dismissAfter:1.0 styleName:JDStatusBarStyleSuccess];
    }
}

+ (void)showStatusBarErrorStr:(NSString *)errorStr
{
    if ([JDStatusBarNotification isVisible])
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
        {
            [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
            [JDStatusBarNotification showWithStatus:errorStr dismissAfter:1.5 styleName:JDStatusBarStyleError];
        });
    }
    else
    {
        [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
        [JDStatusBarNotification showWithStatus:errorStr dismissAfter:1.5 styleName:JDStatusBarStyleError];
    }
}

+ (void)showStatusBarError:(NSError *)error
{
    NSString *errorStr = [NSObject promptWithError:error];
    [NSObject showStatusBarErrorStr:errorStr];
}

#pragma mark - BaseURL
+ (NSString *)baseURLStr
{
    return KbaseURLStr;
}

+ (BOOL)baseURLStrIsTest
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [[defaults valueForKey:@"BaseURLIsTest"] boolValue];
}

+ (void)changeBaseURLStrToTest:(BOOL)isTest
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@(isTest) forKey:@"BaseURLIsTest"];
    [defaults synchronize];
    
    [CDAFNClient changeJsonClient];
    
    [[UINavigationBar appearance] setBackgroundImage: [UIImage imageWithColor:[UIColor colorWithHexString:isTest?@"0x3bbd79": @"0x28303b"]] forBarMetrics:UIBarMetricsDefault];
}

#pragma mark 文件夹 M
//获取fileName的完整地址
+ (NSString* )pathInCacheDirectory:(NSString *)fileName
{
    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cachePaths objectAtIndex:0];
    return [cachePath stringByAppendingPathComponent:fileName];
}

//创建缓存文件夹
+ (BOOL)createDirInCache:(NSString *)dirName
{
    NSString *dirPath = [self pathInCacheDirectory:dirName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    BOOL isCreated = NO;
    if ( !(isDir == YES && existed == YES) )
    {
        isCreated = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (existed) {
        isCreated = YES;
    }
    return isCreated;
}

// 图片缓存到本地
+ (BOOL)saveImage:(UIImage *)image imageName:(NSString *)imageName inFolder:(NSString *)folderName
{
    if (!image) {
        return NO;
    }
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    if ([self createDirInCache:folderName]) {
        NSString * directoryPath = [self pathInCacheDirectory:folderName];
        BOOL isDir = NO;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL existed = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
        bool isSaved = false;
        if ( isDir == YES && existed == YES )
        {
            isSaved = [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:imageName] options:NSAtomicWrite error:nil];
        }
        return isSaved;
    }else{
        return NO;
    }
}
// 获取缓存图片
+ (NSData *)loadImageDataWithName:( NSString *)imageName inFolder:(NSString *)folderName
{
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    NSString * directoryPath = [self pathInCacheDirectory:folderName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL dirExisted = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
    if ( isDir == YES && dirExisted == YES )
    {
        NSString *abslutePath = [NSString stringWithFormat:@"%@/%@", directoryPath, imageName];
        BOOL fileExisted = [fileManager fileExistsAtPath:abslutePath];
        if (!fileExisted) {
            return NULL;
        }
        NSData *imageData = [NSData dataWithContentsOfFile : abslutePath];
        return imageData;
    }
    else
    {
        return NULL;
    }
}

// 删除图片缓存
+ (BOOL)deleteImageCacheInFolder:(NSString *)folderName{
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    return [self deleteCacheWithPath:folderName];
}

//// 网络请求
//+ (BOOL)saveResponseData:(NSDictionary *)data toPath:(NSString *)requestPath
//{
//    User * loginUser = [Login curLoginUser];
//    if (!loginUser)
//    {
//        return NO;
//    }
//    else
//    {
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    if ([self createDirInCache:kPath_ResponseCache])
//    {
//        NSString * abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//        return [data writeToFile:abslutePath atomically:YES];
//    }
//    else
//    {
//        return NO;
//    }
//}

//+ (id) loadResponseWithPath:(NSString *)requestPath
//{   //返回一个NSDictionary类型的json数据
//    User *loginUser = [Login curLoginUser];
//    if (!loginUser)
//    {
//        return nil;
//    }
//    else
//    {
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//    return [NSMutableDictionary dictionaryWithContentsOfFile:abslutePath];
//}
//
//+ (BOOL)deleteResponseCacheForPath:(NSString *)requestPath
//{
//    User *loginUser = [Login curLoginUser];
//    if (!loginUser)
//    {
//        return NO;
//    }
//    else
//    {
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:abslutePath])
//    {
//        return [fileManager removeItemAtPath:abslutePath error:nil];
//    }
//    else
//    {
//        return NO;
//    }
//}

+ (BOOL) deleteResponseCache
{
    return [self deleteCacheWithPath:kPath_ResponseCache];
}

+ (BOOL) deleteCacheWithPath:(NSString *)cachePath
{
    NSString *dirPath = [self pathInCacheDirectory:cachePath];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    bool isDeleted = false;
    if ( isDir == YES && existed == YES )
    {
        isDeleted = [fileManager removeItemAtPath:dirPath error:nil];
    }
    return isDeleted;
}


#pragma mark NetError
-(id)handleResponse:(id)responseJSON
{
    return [self handleResponse:responseJSON autoShowError:YES];
}

-(id)handleResponse:(id)responseJSON autoShowError:(BOOL)autoShowError
{
    NSError *error = nil;
    //code为非0值时，表示有错
    NSNumber *resultCode = [responseJSON valueForKeyPath:@"code"];
    
    if (resultCode.intValue != 0)
    {
        error = [NSError errorWithDomain:[NSObject baseURLStr] code:resultCode.intValue userInfo:responseJSON];
        
        if (resultCode.intValue == 1000 || resultCode.intValue == 3207)
        {   //用户未登录
            kPromptAlert(@"%@", [NSObject promptWithError:error]);
        }
        else
        {
            if (autoShowError)
            {
                [NSObject showError:error];
            }
        }
    }
    return error;
}


@end
